
import express from 'express';
import * as http from 'http';
import * as https from 'https';
import { getExtensionFromContentType, WriteFileTool } from '../utils/WriteFileTool';
import { Generator } from '../utils/Generator';
import { getImageAsBase64, sendHttp } from '../utils/HttpUtil';
import { Config } from '../config/Config';
import { ImgInfo } from '../GOBER';
type HttpClient = typeof http | typeof https;
/**
 * img 接口
 */
export class ImgController {

    async upload_img(req: express.Request, res: express.Response, next: express.NextFunction) {
        try {
            const imgInfo: ImgInfo = req.body
            const wf = WriteFileTool.ins();
            //保存图片
            const fileName = imgInfo.fileName ? imgInfo.fileName : Generator.fileName() + getExtensionFromContentType(imgInfo.contentType);
            wf.writeBytesFile(imgInfo.data, fileName)
            // JSON.stringify(Config.selfStaticUrl + fileName)
            res.status(200).send(Config.selfStaticUrl + fileName).end();
        } catch (error) {
            console.error(error)
            res.status(503).send({
                code: 503,
                msg: error
            })
            return;
        }
    }

    //传入URL通过http请求网络图片并转base64
    async get_img_base64(req: express.Request, res: express.Response) {
        try {
            const url: string = req.body.url;
            if (!url) {
                res.status(501).send({
                    code: 501,
                    msg: '参数不合法'
                })
                return;
            }
            const base64Data = await getImageAsBase64(url);
            res.status(200).send({
                code: 200,
                data: base64Data
            })
        } catch (error) {
            console.log(error);
            res.status(503).send({
                code: 503,
                msg: error
            })
            return;
        }
    }

    mirroApi(req: express.Request, res: express.Response) {
        console.log(req.body);
        res.status(200).send(req.body)
    }

}

var router = express.Router();
const imgController = new ImgController();

router.post('/up_img', imgController.upload_img.bind(imgController));
router.post('/get_img_base64', imgController.get_img_base64.bind(imgController));
router.post('/mirroApi', imgController.mirroApi.bind(imgController));
export default router;
